package accs.model.packstation;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import accs.model.AccountChecker;
import accs.model.Context;
import accs.model.ExtendedHttpClient;
import accs.model.utils.HeaderUtils;
import accs.model.utils.HtmlFormInputCollector;

public class PackstationChecker implements AccountChecker {


	
	public PackstationChecker() {
	}
	
	private static final Pattern SECUREQUESTION_PATTERN=Pattern.compile("value=\"([a-zA-Z0-9.,-]+)\"");
	
	public PackstationAccount login(String mail, String password, Context ctx) throws ClientProtocolException, IOException{
		DefaultHttpClient httpclient=new ExtendedHttpClient(ctx);
				
		HttpGet get=new HttpGet("https://www.paket.de/pkp/appmanager/pkp/desktop?_nfpb=true&_portlet.async=false&_pageLabel=pkp_portal_page_introduction");
		get.setHeader(HeaderUtils.getUserAgent());
		HttpResponse resp=httpclient.execute(get);
		
		List<String> whitelist=new ArrayList<String>(Arrays.asList(new String[]{"headerLogin"}));
		List<NameValuePair> list=HtmlFormInputCollector.collectInputs(new InputStreamReader(resp.getEntity().getContent(),"utf-8"),whitelist);
//		for(NameValuePair bla : list) {
//			System.out.println(bla.getName()+" -> "+bla.getValue());
//		}
		
		HttpPost post=new HttpPost("https://www.paket.de/pkp/appmanager/pkp/desktop?_nfpb=true&_nfls=false&_pageLabel=pkp_portal_page_login&_windowLabel=portletInstance_customerLogin&portletInstance_customerLogin_actionOverride=/de/deutschepost/ubbrief/dhl/pkp/portlets/externallogin/externalLogin&_nfxr=true");
		post.setHeader(HeaderUtils.getUserAgent());
		post.setHeader(HeaderUtils.getReferer("https://www.paket.de/pkp/appmanager/pkp/desktop?_nfpb=true&_portlet.async=false&_pageLabel=pkp_portal_page_introduction"));
		
		list.add(new BasicNameValuePair("dhl_gkuser",mail));
		list.add(new BasicNameValuePair("dhl_gkpass",password));
		post.setEntity(new UrlEncodedFormEntity(list,"UTF-8"));
		
		HttpResponse resp2=httpclient.execute(post);
//		String location=resp2.getFirstHeader("Location").getValue();
		EntityUtils.consume(resp2.getEntity());
//		System.out.println(EntityUtils.toString(resp2.getEntity()));
//     	System.out.println("---------------------------------------------------------------");
		
		HttpGet get2=new HttpGet("https://www.paket.de/pkp/appmanager/pkp/desktop?_nfpb=true&_portlet.async=false&_pageLabel=pkp_portal_page_mydata&_nfls=false");
		get2.setHeader(HeaderUtils.getUserAgent());
		get2.setHeader(HeaderUtils.getReferer("https://www.paket.de/pkp/appmanager/pkp/desktop?_nfpb=true&_portlet.async=false&_pageLabel=pkp_portal_page_introduction"));
		HttpResponse resp3=httpclient.execute(get2);
//		EntityUtils.consume(resp3.getEntity());
//		System.out.println(EntityUtils.toString(resp3.getEntity()));
		
		BufferedReader br=new BufferedReader(new InputStreamReader(resp3.getEntity().getContent(),"utf-8"));
		String line=null;
		
		String name = "";
		String postnr = "";
		String telnumber = "";
		String sonstiges = "";
		String secanswer = "";
		int linenumber = 0;
		boolean valid = true;
		while((line=br.readLine())!=null) {
			line=line.trim(); //System.out.println(line);
			linenumber++;
			
			if(line.contains("<span id=\"header-welcome-username\">")){
//				System.out.println(line);
				name = line.replaceAll("<span id=\"header-welcome-username\">", "").replaceAll("</span>", "").replaceAll("	", "");
			}
			if(line.contains("<h4>Ihre persönliche PostNummer:")){
//				System.out.println(line);
				postnr = line.replaceAll("<h4>Ihre persönliche PostNummer:", "").replaceAll("&nbsp;", "").replaceAll("	", "").replaceAll("</h4>", "");
			}
			if(line.startsWith("<option value=\"") && linenumber < 6000 && line.contains("selected>")){
//				System.out.println(line);
				telnumber = "";
				telnumber += line.substring(line.indexOf("\"")+1, line.lastIndexOf("\""));
			}
			if (line.contains("value=\"") && line.contains("mobilePhoneNumber")) {
//				System.out.println(line);
				telnumber += line.replace("<input type=\"text\" name=\"portletInstance_myData{actionForm.mobilePhoneNumber}\" id=\"mobilePhoneNumber\" class=\"textBox  \" value=\"", "").replace("\" maxlength=\"32\" style=\"width:106px\">", "").replace("\" maxlength=\"32\" readonly style=\"width:106px\">", "");
			}
			if(line.startsWith("<option value=\"") && linenumber > 6000 && line.contains("selected>")){
//				System.out.println(line);
				sonstiges = line.substring(line.indexOf("\"")+1, line.lastIndexOf("\""));
			}
			
			if(line.contains("id=\"passwordReminderValue\"")){
//				System.out.println(line);
				Matcher m=SECUREQUESTION_PATTERN.matcher(line);
				m.find();
				secanswer=m.group(1);
//				System.out.println("Sicherheitsfrage: "+secanswer);
			}
		}
		if(name.length() > 0){
//		System.out.println(line);
		valid=false;
		}
		if(valid){
			PackstationAccount pa = new PackstationAccount(mail, password, name, postnr, telnumber, sonstiges+" "+secanswer);
			return pa;
		}else{
			return null;
		}
	}

	public URL getImage() {
		return PackstationChecker.class.getResource("/accs/gui/img/packstation.png");
	}

	@Override
	public String getName() {
		return "ps";
	}
}